package com.leiyuee.flink.tools;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Yu_Lei
 * @date 2024/6/21
 */

@ConfigurationProperties(prefix = "sharepoint")
@Data
@Configuration
public class SharePointUtils {
    private String username;
    private String password;
    private String siteUrl;
    private String domain;

    // 获取授权
    public String getAuthenticatedResponse(final String urlStr, final String domain,
                                           final String userName, final String password) throws IOException {
        // 设置授权信息
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(domain + "\\" + userName, password.toCharArray());
            }
        });

        // 发起请求获取contextinfo
        URL urlRequest = new URL(urlStr + "/_api/contextinfo");
        HttpURLConnection contextInfoRequest = (HttpURLConnection) urlRequest.openConnection();
        contextInfoRequest.setRequestProperty("Content-Type", "application/json;odata=verbose");
        contextInfoRequest.setRequestProperty("Accept", "application/json;odata=verbose");
        contextInfoRequest.setRequestProperty("Connection", "Keep-Alive");
        contextInfoRequest.setDoOutput(true);
        contextInfoRequest.setDoInput(true);
        contextInfoRequest.setRequestMethod("POST");
        contextInfoRequest.connect();

        // 处理响应
        OutputStream out = contextInfoRequest.getOutputStream();
        out.flush();
        InputStream in = contextInfoRequest.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String str;
        StringBuffer response = new StringBuffer();
        while ((str = br.readLine()) != null) {
            response.append(str);
        }
        String returnValue = new String(response);
//        Map<String, Object> jobj = JSONUtil.toBean(returnValue, Map.class);
        Map<String, Object> jobj = JSONUtil.toBean(returnValue, Map.class);
        Map<String, Object> A1 = (Map<String, Object>) jobj.get("d");
        Map<String, Object> A2 = (Map<String, Object>) A1.get("GetContextWebInformation");
        Object A3 = A2.get("FormDigestValue");
        System.err.println("FormDigestValue: " + A3.toString());

        out.close();
        in.close();
        return A3.toString();
    }



    public List<JSONObject> getTemplateData(String process, String activity) {
        HttpURLConnection connection = null;
        try {
            String apiUrl;
            if (StringUtils.isNotEmpty(process) && StringUtils.isNotEmpty(activity)) {
                apiUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('[相应的站点地址，如果有中文需要进行统一编码，否则会报错]" + URLEncoder.encode(process, "UTF-8") + "/" + URLEncoder.encode(activity, "UTF-8") + "')/files";
            } else {
                apiUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('[相应的站点地址，如果有中文需要进行统一编码，否则会报错]')/files";
            }
            URL url = new URL(apiUrl);
            CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/json;odata=verbose");//请求头中设置ContentType对应值
            connection.setRequestProperty("Accept", "application/json;odata=verbose");//请求头中设置Accept对应值
            connection.setRequestProperty("X-RequestDigest", getAuthenticatedResponse(siteUrl, domain, username, password));
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(domain + "\\" + username, password.toCharArray());
                }
            });
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            if (StringUtils.isNotEmpty(response)) {
                ArrayList<JSONObject> sharePointResultDTOS = new ArrayList<>();
                //对获取到的数据进行相应的解析 …………
                return sharePointResultDTOS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
